/**
 * 
 */
package com.music.auth.filters;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.music.auth.logging.AuthLogger;

/**
 * @author asanthan
 * 
 */
public class LoginRequiredFilter implements Filter {
	private String mLoginPath;

	private static final Logger log = AuthLogger.getLogger();

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		log.info("Login Required filter destroying");
		// Do nothing.
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest pRequest, ServletResponse pResponse,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) pRequest;
		HttpServletResponse response = (HttpServletResponse) pResponse;
		log.debug("Entering Login Required Filter");
		// Check whether user is logged in.

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user != null) {
			request.setAttribute("user", user);
			log.debug("Logged-in email:"+user.getEmail());
			chain.doFilter(pRequest, pResponse);
		} else {
			String encodedUrl = URLEncoder.encode(request.getRequestURI(),"UTF-8");
			response.sendRedirect(getLoginPath()+"?return="+encodedUrl);
		}
		
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig arg0) throws ServletException {
		log.info("Login Required filter initializing");
		// no initialising now.
	}

	/**
	 * @return the loginPath
	 */
	public String getLoginPath() {
		return mLoginPath;
	}

	/**
	 * @param pLoginPath the loginPath to set
	 */
	
	public void setLoginPath(String pLoginPath) {
		mLoginPath = pLoginPath;
	}

	

}
